package com.ocom.app.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ocom.app.feignclient.MqSimpleFeignClint;
import com.ocom.app.properties.SmsProperties;
import com.ocom.common.entity.app.EntityTLoginAccount;
import com.ocom.common.entity.app.EntityTUser;
import com.ocom.app.service.TLoginAccountService;
import com.ocom.app.service.TUserService;
import com.ocom.app.utils.AESExample;
import com.ocom.common.enums.AccountTypeEnuM;
import com.ocom.common.utils.DateUtil;
import com.ocom.common.vo.app.FindOrRegVo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.simple.SmsRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.constant.AppUrl;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.StringUtil;
import com.ocom.redis.util.RedisUtil;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import java.text.ParseException;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
public class TUserController {


  @Autowired
  private RedisUtil redisUtil;

  @Autowired
  private RedisTemplate redisTemplate;

  @Autowired
  private MqSimpleFeignClint mqSimpleFeignClint;

  @Autowired
  private TUserService tUserService;

  @Autowired
  private TLoginAccountService tLoginAccountService;

  @Autowired
  private SmsProperties smsProperties;

  @GetMapping("/campus/sendsms")
  public Result sendSms(@RequestParam("phoneNum") String phoneNum) {
    // 校验手机号是否合法
    if (StringUtil.isEmpty(phoneNum) || !StringUtil.isPhone(phoneNum)) {
      return ResultUtil.error(ResultEnum.Err_4705);
    }

    if (!redisUtil.lock("app:smsPhone:" + phoneNum, 60)) {
      return ResultUtil.error(ResultEnum.Err_4700);
    }

    // 3，验证手机号是否超过当日发送最大值。(通过redis实现)
    //checkSendLimit
    Integer maxSendCount = 20;

    String limitKey = "send:telephone:limit:";
    Object o = redisTemplate.opsForValue().get(limitKey + phoneNum);

    Integer count = ObjectUtil.isNotNull(o) ? (Integer) o : 0;
    if (count >= maxSendCount) {
      return ResultUtil.error(ResultEnum.Err_4701);
    }
    // 验证码一天
    redisTemplate.opsForValue().set(limitKey + phoneNum, ++count, 86400l, TimeUnit.SECONDS);

    String codeKey = "send:telephone:code:";
    // 5，如返回一条正确的数据，则调发送短信的接口。并将发送的短信验证码写入redis
    String code = RandomUtil.randomNumbers(6);

    // 验证码5分钟
    redisTemplate.opsForValue().set(codeKey + phoneNum, code, 300l, TimeUnit.SECONDS);
    // 发送短信
    SmsRequest smsRequest = new SmsRequest();
    smsRequest.setSecretId(smsProperties.getSecretId());
    smsRequest.setSecretKey(smsProperties.getSecretKey());
    smsRequest.setSignName(smsProperties.getSignName());
    smsRequest.setSdkAppId(smsProperties.getSdkAppId());
    smsRequest.setTemplateId(smsProperties.getTemplateId());
//    smsRequest.setSecretId("AKIDcLzhN0a8e8eChEnaQG8zpifcabfnu5JX");
//    smsRequest.setSecretKey("Kh6VozznPn13ECwSlphN9jCVaRLTPIPa");
//    smsRequest.setSignName("鑫澳康科技");
//    smsRequest.setSdkAppId("1400314290");
//    smsRequest.setTemplateId("1545715");
    smsRequest.setPhone(phoneNum);
    smsRequest.getParams().add(code);
    return ResultUtil.success(mqSimpleFeignClint.FySms(smsRequest).getData());
  }

  /**
   * 3.1.查询并注册(/feign/user/findOrRegByPhoneNum)
   *
   * @param phoneNum
   * @return
   */
  @GetMapping(AppUrl.URL_FeignUserFindOrRegByPhoneNum)
  public Result findOrRegByPhoneNum(@RequestParam("phoneNum") String phoneNum,@RequestParam("code") String code)
      throws ParseException {
    // 校验手机号是否合法
    if (StringUtil.isEmpty(phoneNum) || !StringUtil.isPhone(phoneNum)) {
      return ResultUtil.error(ResultEnum.Err_4705);
    }
    String codeKey = "send:telephone:code:";
    String codeRedis = (String) redisTemplate.opsForValue().get(codeKey + phoneNum);

    if (!StringUtils.equalsAny(code, "8888", "123456")) {
      if (!StringUtils.equals(code, codeRedis)) {
        return ResultUtil.error(ResultEnum.Err_4704);
      }
    }
    // 验证通过删除验证码
    if (!StringUtils.equalsAnyIgnoreCase(code, "123456", "8888")) {
      redisTemplate.delete(codeKey + phoneNum);
    }

    FindOrRegVo findOrReg = tUserService.findOrRegByPhoneNum(phoneNum);

    if (ObjectUtil.isNotNull(findOrReg)) {
      return ResultUtil.success(findOrReg);
    }
    // 获取当前时间
    String dateTime = DateUtil.getDateTime();
    Date createTime = DateUtil.getDate(dateTime, "yyyy-MM-dd HH:mm:ss");
    EntityTUser tUser = new EntityTUser();
    Long id =  IdWorker.getId();;
    tUser.setUserName(phoneNum);
    tUser.setId(id);
    tUser.setCreateTime(createTime);
    tUser.setUpdateTime(createTime);
    tUserService.save(tUser);
    EntityTLoginAccount tLoginAccount = new EntityTLoginAccount();
    tLoginAccount.setUserId(id);
    tLoginAccount.setTelelePhone(phoneNum);
    tLoginAccount.setType(AccountTypeEnuM.telelePhone.getValue());
    tLoginAccount.setCreateTime(createTime);
    tLoginAccount.setUpdateTime(createTime);
    tLoginAccountService.save(tLoginAccount);

    return ResultUtil.success(tUserService.findOrRegByPhoneNum(phoneNum));

  }

  @GetMapping("/user/campus/redirectCode")
  public Result userCampusRedirectCode() {
    YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
    Long id = yoCiUser.getId();
    String ocom2024Ocom2024 = AESExample.encrypt(id.toString(), "Ocom2024Ocom2024");
    return ResultUtil.success(ocom2024Ocom2024);
  }

  //账号销毁
  @PostMapping("/user/campus/destroy")
  public Result destroy(){
    YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
    assert yoCiUser != null;
    this.tUserService.destroy(yoCiUser.getId());
    return ResultUtil.success();
  }
}

